package dao

import (
	dom "a-common/domain"
	"a-system/domain/entity"
	"strings"
	"sync"

	"xorm.io/builder"
)

var (
	sysPostDaoTemp *SysPostDao
	sysPostDaoOnce sync.Once
)

type SysPostDao struct{}

func NewSysPostDao() *SysPostDao {
	sysPostDaoOnce.Do(func() {
		sysPostDaoTemp = &SysPostDao{}
	})
	return sysPostDaoTemp
}

// List 列表
func (m *SysPostDao) List(args *entity.SysPostDto, isExprot bool) (dom.PageVo, error) {
	// 构建查询条件
	query := pgCli.Table(&entity.SysPost{}).Where("1 = 1")
	if args.PostCode != "" {
		query.And("post_code = ?", args.PostCode)
	}
	if args.PostName != "" {
		query.And("post_name = ?", args.PostName)
	}
	if args.Status != "" {
		query.And("status = ?", args.Status)
	}

	// 查询
	var vPage dom.PageVo
	if isExprot {
		var rows []entity.SysPostExportVo
		total, err := query.Limit(args.PageSize, (args.PageNum-1)*args.PageSize).Asc("post_id").FindAndCount(&rows)
		if err != nil {
			return vPage, err
		}
		vPage.Rows = rows
		vPage.Total = total
	} else {
		var rows []entity.SysPostPageVo
		total, err := query.Limit(args.PageSize, (args.PageNum-1)*args.PageSize).Asc("post_id").FindAndCount(&rows)
		if err != nil {
			return vPage, err
		}
		vPage.Rows = rows
		vPage.Total = total
	}
	vPage.PageNum = args.PageNum
	vPage.PageSize = args.PageSize
	return vPage, nil
}

// ListAll 查询全部
func (m *SysPostDao) ListAll() ([]entity.SysPostVo, error) {
	var rows []entity.SysPostVo
	err := pgCli.Table(&entity.SysPost{}).Where("1 = 1").Asc("post_sort").Find(&rows)
	if err != nil {
		return rows, err
	}
	return rows, nil
}

// Get 查
func (m *SysPostDao) Get(id string) (entity.SysPostVo, error) {
	var v entity.SysPostVo
	_, err := pgCli.Table(&entity.SysPost{}).ID(id).Get(&v)
	return v, err
}

// Add 增
func (m *SysPostDao) Add(args *entity.SysPostDto) (int64, error) {
	return pgCli.InsertOne(&entity.SysPost{
		PostCode: args.PostCode,
		PostName: args.PostName,
		PostSort: args.PostSort,
		Status:   args.Status,
		BaseStruct: dom.BaseStruct{
			CreatedBy: args.CreatedBy,
			UpdatedBy: args.CreatedBy,
			Remark:    args.Remark,
		},
	})
}

// Edit 改
func (m *SysPostDao) Edit(args *entity.SysPostDto) (int64, error) {
	return pgCli.ID(args.PostId).Update(&entity.SysPost{
		PostCode: args.PostCode,
		PostName: args.PostName,
		PostSort: args.PostSort,
		Status:   args.Status,
		BaseStruct: dom.BaseStruct{
			UpdatedBy: args.UpdatedBy,
			Remark:    args.Remark,
		},
	})
}

// Del 删
func (m *SysPostDao) Del(ids string) (int64, error) {
	return pgCli.In("post_id", strings.Split(ids, `,`)).Delete(&entity.SysPost{})
}

// GetPostByUserId 通过用户ID获取部门
func (m *SysPostDao) GetPostByUserId(userId int64) ([]entity.SysPostVo, error) {
	var v []entity.SysPostVo
	// 嵌套查询
	err := pgCli.Table(&entity.SysPost{}).In("post_id", builder.Select("post_id").From("sys_user_post").Where(builder.Eq{"user_id": userId})).Find(&v)
	return v, err
}
